<script setup lang="jsx">
import { ref, watch } from 'vue';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { addNotice, upNotice } from '@/service/api';

const props = defineProps({
  currentRow: {
    type: Object,
    default: () => null
  },
  operateType: {
    type: String,
    default: () => null
  }
});

const emit = defineEmits(['success']);

const { formRef, validate } = useAntdForm();
const { createRequiredRule } = useFormRules();
const rules = {
  noticeTitle: createRequiredRule('请输入公告标题'),
  noticeType: createRequiredRule('请输入公告类型'),
  noticeContent: createRequiredRule('请输入内容')
};

const model = ref({
  noticeTitle: null,
  noticeType: null,
  status: '0',
  noticeContent: null
});

async function submitForm() {
  if (!props.operateType) return;
  await validate();
  let pro;
  if (props.operateType === 'edit') {
    pro = upNotice({
      noticeId: props.currentRow.noticeId,
      ...model.value
    });
  } else {
    pro = addNotice(model.value);
  }
  pro.then(({ error }) => {
    if (!error) {
      window?.$message?.success('操作成功!');
      emit('success');
    }
  });
}

watch(
  () => props.currentRow,
  val => {
    if (val) {
      console.log('val :>> ', val);
      const { noticeTitle, noticeType, status, noticeContent } = val;
      model.value = { noticeTitle, noticeType, status, noticeContent };
    } else {
      model.value = {
        noticeTitle: null,
        noticeType: null,
        status: '0',
        noticeContent: null
      };
    }
  },
  {
    deep: true,
    immediate: true
  }
);

defineExpose({
  submitForm
});
</script>

<template>
  <AForm ref="formRef" :model="model" :rules="rules" :label-col="{ lg: 8, xs: 4 }" label-wrap>
    <ARow :gutter="20">
      <ACol :lg="24" :xs="24">
        <AFormItem name="noticeTitle" label="公告标题" :label-col="{}">
          <AInput v-model:value="model.noticeTitle" placeholder="请输入公告标题" autocomplete="off"></AInput>
        </AFormItem>
      </ACol>
      <ACol :lg="24" :xs="24">
        <AFormItem name="noticeType" label="公告类型" :label-col="{}">
          <!-- <AInput v-model:value="model.noticeType" placeholder="请输入公告类型" autocomplete="off"></AInput> -->
          <ARadioGroup v-model:value="model.noticeType">
            <ARadio value="1">通知</ARadio>
            <ARadio value="2">公告</ARadio>
          </ARadioGroup>
        </AFormItem>
      </ACol>
      <ACol :lg="24" :xs="24">
        <AFormItem name="status" label="状态" :label-col="{}">
          <ARadioGroup v-model:value="model.status">
            <ARadio value="0">正常</ARadio>
            <ARadio value="1">关闭</ARadio>
          </ARadioGroup>
        </AFormItem>
      </ACol>
      <ACol :lg="24" :xs="24" class="mt-15px">
        <AFormItem name="noticeContent" label="内容" :label-col="{}">
          <ATextarea v-model:value="model.noticeContent" placeholder="请输入内容" :rows="4" autocomplete="off" />
        </AFormItem>
      </ACol>
    </ARow>
  </AForm>
</template>

<style></style>
